<template>
  <div class="web">
    <div class="webLeft">
      <menuleft
        :menuList="menuList"
        @handleMenu="handleMenu"
        :menuFlag="menuFlag"
      />
    </div>
    <div class="webRight">
      <a-breadcrumb separator=">">
        <a-breadcrumb-item>
          <router-link
            :to="{ path: '/suggest', query: { menuFlag: this.menuFlag } }"
            >内部交流</router-link
          >
        </a-breadcrumb-item>
        <a-breadcrumb-item>详情</a-breadcrumb-item>
      </a-breadcrumb>

      <div>
        <div class="title">{{ listData.title }}</div>
        <el-row type="flex" justify="space-between" class="description-div">
          <el-col :span="6">
            <div class="description">
              {{ listData.authorName }} 发布于 {{ listData.createTime }}
            </div>
          </el-col>
          <el-col :span="4" class="rh">
            <span
              class="actions-span"
              v-for="i in listData.actions"
              v-show="i.isShow"
              :key="i.type"
              @click="handleOperation(i.text)"
            >
              <a-icon
                :theme="i.theme"
                :type="i.type"
                :style="{ marginRight: '8px', color: i.color }"
              />
              {{ i.text }}
            </span>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col>
            <div class="content content-detail" v-html="listData.content"></div>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col>
            <div class="enclosure-div">
              <span class="enclosure">附件下载：</span>
              <el-button
                type="text"
                @click="download(i)"
                v-for="(i, index) in listData.fileList"
                :key="index"
                >{{ i.name }}</el-button
              >
            </div>
          </el-col>
        </el-row>
      </div>

      <div class="divide-line"></div>

      <CommentReply :articleId="articleId" />
      <!-- 修改文章 -->
      <el-dialog
        :close-on-click-modal="false"
        class="article-dialog"
        title="修改文章"
        :visible.sync="visible"
        center
        width="70%"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title"></el-input>
          </el-form-item>

          <el-form-item label="文章类型" prop="typeId">
            <el-select v-model="typeId" placeholder="选择文章类型" clearable>
              <el-option
                v-for="item in menuList[0].children"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章">
            <quill-editor
              style="height: 450px"
              v-model="form.content"
              ref="myQuillEditor"
              :options="editorOption"
            ></quill-editor>
          </el-form-item>
          <el-form-item label="上传文件" style="margin-top: 100px">
            <el-upload
              :headers="headers"
              action="/api/upload/uploadFile/9"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :file-list="form.fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="sureUpdate" :loading="loading"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import CommentReply from "./components/commentReply";
import { mixin } from "../../../mixin/mixin";
import bus from "@/components/bus";
import {
  getExchangeList,
  getArticleDetail,
  editArticleDetail,
  deleteArticleDetail,
  likeArticle,
  downloadFile,
} from "../../../service/Api";
import typeArr from "@/utils/typeArr";

export default {
  name: "articleListDetail",
  components: { CommentReply },
  mixins: [mixin],
  data() {
    return {
      headers: {
        "API-User-Token": sessionStorage.getItem("token"), //文件上传需携带token
      },
      listData: {}, //文章加载出来的原先数据
      loading: false,
      form: {}, //修改文章弹出框数据源
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { required: true, message: "请输入标题", trigger: "change" },
          { min: 3, max: 100, message: "长度应该是3到100", trigger: "blur" },
          { min: 3, max: 100, message: "长度应该是3到100", trigger: "change" },
        ],
      },
      //修改文章弹出框富文本默认内容
      editorOption: {
        theme: "snow",
        placeholder: "请输入文本...",
      },
      visible: false, //修改文章的对话框弹出是否可见
      menuFlag: "",
      typeId: "",
      menuList: [
        {
          name: "内部交流",
          id: "0",
          children: [],
        },
      ],
      articleId: this.articleId,
      fileTypeArr: typeArr,
    };
  },
  watch: {
    "$route.query"(n, o) {
      this.articleId = this.$route.query.id;
      this.menuFlag = this.$route.query.menuFlag;
    },
  },
  mounted() {
    this.articleId = this.$route.query.id;
    this.menuFlag = this.$route.query.menuFlag;
    this.getExchangeList();
    this.getArticleDetail();
  },
  methods: {
    //文章内容附件修改相关事件
    handleRemove(file, fileList) {
      let index = this.form.fileList.findIndex((x) => x.name === file.name);
      console.log(index);
      if (index !== -1) {
        this.form.fileList.splice(index, 1);
      }
      let arr = [];
      arr = this.form.fileList.map((x) => x.name);
      let arr1 = [];
      arr1 = this.form.fileList.map((x) => x.path);
      this.$set(this.form, "annexTitle", arr.join());
      this.$set(this.form, "annexPath", arr1.join());
    },
    handleSuccess(res, file, fileList) {
      let obj = {};
      obj = {
        name: file.name,
        path: res.data.fileIds,
        status: file.status,
        uid: file.uid,
      };
      let index = this.form.fileList.findIndex((x) => x.name === obj.name);
      if (index !== -1) {
        this.form.fileList.splice(index, 1);
      }
      this.form.fileList.push(obj);
      let arr = [];
      arr = this.form.fileList.map((x) => x.name);
      let arr1 = [];
      arr1 = this.form.fileList.map((x) => x.path);
      this.$set(this.form, "annexTitle", arr.join());
      this.$set(this.form, "annexPath", arr1.join());
    },
    //===================================================
    getExchangeList() {
      getExchangeList().then((res) => {
        let moduleName = res.data;
        let obj = {};

        moduleName.forEach((item, index) => {
          obj = {
            id: item.id,
            name: item.moduleName,
            flag: true,
          };

          this.menuList[0].children.push(obj);
        });
      });
    },
    handleMenu(id) {
      this.menuFlag = id;
      this.$router.push({
        path: "/suggest",
        query: {
          menuFlag: this.menuFlag,
        },
      });
    },
    getArticleDetail() {
      getArticleDetail(this.articleId).then((res) => {
        if (res != undefined) {
          let titleList = res.data.annexTitle.split(",").filter((item) => {
            return item != "";
          });

          let pathlist = res.data.annexPath.split(",").filter((item) => {
            return item != "";
          });

          let fileList = [];
          let obj = {};
          for (let i in titleList) {
            obj = {
              name: titleList[i],
              path: pathlist[i],
            };
            fileList.push(obj);
          }

          this.listData = {
            ...res.data,
            titleList: titleList,
            fileList: fileList,
            actions: [
              {
                type: "edit",
                text: "修改",
                color: "#409EFF",
                isShow: res.data.canUpAndDel,
              },
              {
                type: "delete",
                text: "删除",
                color: "#F56C6C",
                isShow: res.data.canUpAndDel,
              },
              {
                type: "like-o",
                text: res.data.zanCount,
                color: res.data.loginIfZan == 0 ? "#00B98D" : "#909399",
                isShow: true,
                theme: res.data.loginIfZan == 0 ? "filled" : "outlined",
              },
            ],
          };
          //获取到用户最先填写的标题内容等信息  复制给form 在修改文章弹出框中展示
          this.$set(this.form, "content", this.listData.content);
          this.$set(this.form, "title", this.listData.title);
          this.$set(this.form, "annexPath", this.listData.annexPath);
          this.$set(this.form, "annexTitle", this.listData.annexTitle);
          this.$set(this.form, "fileList", this.listData.fileList);
          console.log(this.form);
        } else {
          this.listData = {};
        }
      });
    },
    handleOperation(text) {
      if (text == "修改") {
        this.visible = true;
        this.typeId = Number(this.menuFlag);
      } else if (text == "删除") {
        deleteArticleDetail(this.listData.id).then((res) => {
          this.$nextTick(() => {
            bus.$emit("updateList");
          });

          this.$router.push({
            path: "/suggest",
            query: { menuFlag: this.menuFlag },
          });
          this.$message.success("删除成功！");
        });
      } else {
        likeArticle(this.listData.id).then((res) => {
          if (this.listData.loginIfZan == 0) {
            this.$message.info("已取消点赞！");
          } else {
            this.$message.success("点赞成功！");
          }
          this.getArticleDetail();
        });
      }
    },

    //点击确定 修改文章内容时
    sureUpdate() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          //确认修改文章内容的时候 将客户修改之后的form又复制给listData
          this.listData = Object.assign(this.listData, this.form);
          console.log(this.listData);
          editArticleDetail({
            id: this.listData.id,
            title: this.listData.title,
            content: this.listData.content,
            annexTitle: this.listData.annexTitle,
            annexPath: this.listData.annexPath,
            moduleId: this.typeId,
          }).then((res) => {
            if (res.data == 0) {
              this.getArticleDetail();
              this.$message.success("修改成功！");
              this.loading = false;
            }
          });
          this.visible = false;
        } else {
          this.$message.info("请检查填写的信息");
          return false;
        }
      });
    },
    //点击文章内容附件下载
    download(file) {
      console.log(file);
      this.$confirm("此操作将下载文档, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then((_) => {
        // var a = document.createElement("a");
        // var event = new MouseEvent("click");
        // a.download = file.name;
        // a.href = file.path;
        // a.dispatchEvent(event);

        fetch(file.path).then(async (res) => {
          let data = await res.blob();
          var link = document.createElement("a");
          var body = document.querySelector("body");
          link.href = window.URL.createObjectURL(data);
          let arr = this.fileTypeArr.filter((el) => {
            if (file.path.indexOf(el) !== -1) {
              return el;
            }
          });
          if (arr.length > 0) {
            link.download = file.name;
          } else {
            link.download = file.name + arr[0];
          }
          link.style.display = "none";
          body.appendChild(link);
          link.click();
          body.removeChild(link);
          window.URL.revokeObjectURL(link.href);
        });
      });
    },
  },
};
</script>

<style scoped>
@import "../../../styles/common.css";

.ant-list-item-meta-title {
  margin-bottom: 12px;
}

.title {
  font-size: 20px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(48, 49, 51, 1);
  margin-top: 10px;
}

.description-div {
  margin: 20px 0 30px 0;
}

.description {
  font-family: Microsoft YaHei;
  color: rgba(144, 147, 153, 1);
}

.content {
  font-family: Microsoft YaHei;
  color: rgba(96, 98, 102, 1);
}

.content-btn {
  /* margin-top: 15px; */
  margin-bottom: 15px;
  text-align: right;
}

.actions-span {
  margin-right: 10px;
  cursor: pointer;
  color: rgba(144, 147, 153, 1);
}

.word {
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(96, 98, 102, 1);
  line-height: 21px;
  margin-top: 12px;
}

.enclosure-div {
  margin: 25px 0;
}

.enclosure {
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(48, 49, 51, 1);
}

.divide-line {
  height: 1px;
  background: rgba(238, 238, 238, 1);
}

.content-div {
  border: 1px solid #d9d9d9;
}
</style>